package com.qdxht.dispenser.utils;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import timber.log.Timber;

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2020/08/12
 *    desc   : 自定义日志打印规则
 */
public final class DebugLoggerTree extends Timber.DebugTree {

    private static final int MAX_TAG_LENGTH = 23;

    Context context;

    public DebugLoggerTree(Context context){
        this.context = context;
    }

    /**
     * 创建日志堆栈 TAG
     */
    @Override
    protected String createStackElementTag(@NotNull StackTraceElement element) {
        String tag = "(" + element.getFileName() + ":" + element.getLineNumber() + ")";
        // 日志 TAG 长度限制已经在 Android 8.0 被移除
        if (tag.length() <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tag;
        }
        return tag.substring(0, MAX_TAG_LENGTH);
    }

    @Override
    protected void log(int priority, String tag, @NonNull String message, Throwable t) {
//        File file = new File(CacheDiaPath + "/"+tag+".txt");
        File file = new File(Environment.getExternalStorageDirectory() + "/logs.txt");
        Log.v("日志存储路径", "file.path:" + file.getAbsolutePath() + ",message:" + message);
        FileWriter writer = null;
        BufferedWriter bufferedWriter = null;
        try {
            writer = new FileWriter(file,true);
            bufferedWriter = new BufferedWriter(writer);
            bufferedWriter.write(DateUtil.getFormatDate() +" " + tag + " - "+ message+"\n");
            bufferedWriter.flush();
        }catch (IOException e) {
            Log.v("dyp", "存储文件失败");
            e.printStackTrace();
        }finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}